﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QNetworkInterface>


typedef IceUtil::Handle<MySessionCB> MySessionCBPtr;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_pCallBackCtrl = new CallBackCtrlI();
    connect(m_pCallBackCtrl,SIGNAL(sig_write_text(QString)),this,SLOT(slot_wrtie_text(QString)));
    m_pSessionCallBack = new MySessionCB();
    connect(m_pSessionCallBack,SIGNAL(sig_Notify(int,QString)),this,SLOT(slot_notify(int,QString)));
    m_timer = new QTimer();
    connect(m_timer,SIGNAL(timeout()),this,SLOT(time_out()));
}

MainWindow::~MainWindow()
{
    m_prxRegCallBack->unInstall("50-7B-80-50-4F-6D");
    delete ui;
}

void MainWindow::init()
{
}

void MainWindow::on_pushButton_clicked()
{
    QString m_connIP = ui->lineEdit->text();

    Ice::InitializationData iniData;
    iniData.properties = Ice::createProperties();
    iniData.properties->setProperty(QString("Ice.Default.Router").toUtf8().toStdString(), QString("Glacier2/router:tcp -p 8989 -h %1 -t 2000\r\n").arg(m_connIP).toUtf8().toStdString());
    iniData.properties->setProperty(QString("Callback.CallbackServer").toUtf8().toStdString(), QString("callback:tcp -p 12345:udp -p 12345\r\n").toUtf8().toStdString());
    iniData.properties->setProperty(QString("Callback.Client.Endpoints").toUtf8().toStdString(), QString("tcp:udp\r\n").toUtf8().toStdString());
    //iniData.properties->setProperty(QString("Ice.Warn.Connections").toUtf8().toStdString(), QString("1\r\n").toUtf8().toStdString());


    _factory = new Glacier2::SessionFactoryHelper(iniData, m_pSessionCallBack);
    QString strMac = "50-7B-80-50-4F-6D";
    QString strPwd = "bb";
    QString strId = QString("{\"type\":\"robot\",\"name\":\"%1\"}").arg(strMac);
    _session = _factory->connect(strId.toUtf8().toStdString(), strPwd.toUtf8().toStdString());

//    Ice::CommunicatorPtr ice = Ice::initialize(iniData);

//    QString strMac = "50-7B-80-50-4F-6D";
//    QString strPwd = "bb";
//    Ice::RouterPrx defaultRouter = ice->getDefaultRouter();
//    Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(defaultRouter);
//    try{
//        router->createSession(strMac.toUtf8().toStdString(), strPwd.toUtf8().toStdString()); //创建基于密码方式的session
//    }catch(Ice::Exception& e){
//        qDebug()<<"error:"<<e.what();
//    }

}
void MainWindow:: slot_notify(int state, const QString &content)
{
    switch (state) {
    case MySessionCB::STT_CREATEDCOMMUNICATOR:

        break;
    case MySessionCB::STT_CONNECTED:
        installCallBack();
        break;
    case MySessionCB::STT_DISCONNECTED:
        _session = 0;
        _factory->destroy();
        break;
    case MySessionCB::STT_CONNECTFAILED:
        break;
    default:
        break;
    }
    qDebug()<<content;
}

void MainWindow::slot_wrtie_text(QString text)
{
   ui->listWidget_text->addItem(text);
   ui->listWidget_text->setCurrentRow(ui->listWidget_text->count()-1);
}
void MainWindow::installCallBack(){
    try
    {
        Ice::ObjectAdapterPtr adapter = _session->communicator()->createObjectAdapter("Callback.Client");
        adapter->add(m_pCallBackCtrl, _session->communicator()->stringToIdentity("CallBack"));
        adapter->activate();

        m_prxCallBack = NetWorkRobot::CallBackPrx::uncheckedCast(adapter->createProxy(_session->communicator()->stringToIdentity("CallBack")));
        m_timer->start(10000);
        QString strMac = getHostMacAddress();
        QString strInfo = QString("{\"type\":\"robot\",\"data\":{\"robotMac\":\"%1\",\"password\":\"22\",\"type\":\"V1\",\"version\":\"2.0\",\"AVadress\":\"192.168.101.186\"}}").arg(strMac);

        m_prxRegCallBack = NetWorkRobot::RegCallBackPrx::checkedCast(_session->communicator()->stringToProxy("RegCallBack"));
        bool m_b = m_prxRegCallBack->install(m_prxCallBack,strInfo.toUtf8().toStdString());
        if(m_b){
            qDebug()<<"connect success!";
            ui->listWidget_text->addItem("connect success!");
        }
    }catch(Ice::Exception& e){
        qDebug()<<"installCallBack Error:"<<e.what();
        return;
    }
}


void MainWindow::time_out()
{
    m_prxCallBack->ice_ping();
}

QString MainWindow:: getHostMacAddress()
{
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    QString strMacAddr = "";
    for(int i = 0; i < nCnt; i ++)
    {
        // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning) && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }
    strMacAddr = "50-7B-80-50-4F-6D";
    return strMacAddr;
}

